const fs = require('fs');
const promisify = require('util').promisify;
const path = require('path');
const ejs = require('ejs');
// const conf = require('../config/defaultConfig');
const compress = require('./compress');
const range = require('./range');
const isFresh = require('./cache');

const mime = require('./mime');
const tplPath = path.join(__dirname, '../tpl/index.html');
const source = fs.readFileSync(tplPath);
const template = ejs.compile(source.toString());

const stat = promisify(fs.stat);
const readdir = promisify(fs.readdir);

module.exports = async function (req, res, filePath, conf) {
	try {
		const status = await stat(filePath);
		if (status.isFile()) {
			const contentType = mime(filePath)
			res.setHeader('content-Type', contentType);
			// 拦截判断是否走缓存
			if(isFresh(status, req, res)){
				res.statusCode = 304;
				res.end();
				return
			}

			let rs;
			const {code, start, end} = range(status.size, req, res);
			if(code ===200) {
				res.statusCode = 200;
				rs = fs.createReadStream(filePath);
			}else if(code === 206) {
				res.statusCode = 206
				// fs.createReadStream(path, [options]) options 可以通过start 和 end 设置 文件 可读取的字节数范围，而不是读取整个文件。
				rs = fs.createReadStream(filePath, {start, end});
			}
			if(filePath.match(conf.compress)){
				rs = compress(rs, req, res)
			}
			rs.pipe(res);
		} else if (status.isDirectory()) {
			const files = await readdir(filePath)
			const dir = path.relative(conf.root, filePath);
			res.statusCode = 200;
			res.setHeader('content-Type', 'text/html');
			const data = {
				files,
				title: path.basename(filePath),
				dir: dir ? `/${dir}` : ''
			}
			res.end(template(data))
		}
	} catch (error) {
		res.statusCode = 404;
		res.setHeader('content-Type', 'text/plain');
		res.end(`${filePath} is not destorey ${error}`);
		return
	}
}
